/**
 * 封装基础请求库
 */
export default class Request {
	/* 基础默认配置 */
	config = {
		baseUrl: '',
		header: {
			'content-type': 'application/x-www-form-urlencoded'
		},
		method: 'GET',
		dataType: 'json',
		responseType: 'text'
	}

	/* 判断url是否为绝对路径 */
	static isAbsoluteUrl(url) {
		return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
	}

	// 对象转 &key=params[key]
	static addQueryString(params) {
		let paramsData = ''
		Object.keys(params).forEach(function(key) {
			paramsData += key + '=' + params[key] + '&'
		})
		return paramsData.substring(0, paramsData.length - 1)
	}

	/**
	 * @property {Function} request 请求拦截器
	 * @property {Function} response 响应拦截器
	 * @type {request: Request.interceptor.request, response: Request.interceptor.response}
	 */
	interceptor = {
		/**
		 * @param {Request~requestCallback} cb - 请求之前拦截,接收一个函数（config, cancel）=> {return config}。第一个参数为全局config,第二个参数为函数，调用则取消本次请求。
		 */
		request: (cb) => {
			if (cb) {
				this.requestBeforeFun = cb
			}
		},
		/**
		 * @param {Request~responseCallback} cb 响应拦截器，对响应数据做点什么
		 * @param {Request~responseErrCallback} ecb 响应拦截器，对响应错误做点什么
		 */
		response: (cb, ecb) => {
			if (cb && ecb) {
				this.requestComFun = cb
				this.requestComFail = ecb
			}
		}
	}
	// 请求前调用函数
	requestBeforeFun(config) {
		return config
	}
	// 请求成功调用函数
	requestComFun(response) {
		return response
	}
	// 请求失败调用函数
	requestComFail(response) {
		return response
	}

	/**
	 * 自定义验证器，如果返回true 则进入响应拦截器的响应成功函数(resolve)，否则进入响应拦截器的响应错误函数(reject)
	 * @param { Object } response - 请求响应体（只读）
	 * @return { Boolean } 如果为true,则 resolve, 否则 reject
	 */
	validateStatus(response) {
		return true
	}


	// 设置全局默认配置
	setConfig(f) {
		this.config = f(this.config)
	}

	/**
	 * @Function
	 * @param {Object} options - 请求配置项
	 * @prop {String} options.url - 请求路径
	 * @prop {Object} options.data - 请求参数
	 * @prop {Object} [options.responseType = config.responseType] [text|arraybuffer] - 响应的数据类型
	 * @prop {Object} [options.dataType = config.dataType] - 如果设为 json，会尝试对返回的数据做一次 JSON.parse
	 * @prop {Object} [options.header = config.header] - 请求header
	 * @prop {Object} [options.method = config.method] - 请求方法
	 * @returns {Promise<unknown>}
	 */
	async request(options = {}) {
		options.baseUrl = this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.responseType = options.responseType || this.config.responseType
		options.url = options.url || ''
		options.data = options.data || {}
		options.params = options.params || {}
		options.header = options.header || this.config.header
		options.method = options.method || this.config.method
		return new Promise(async (resolve, reject) => {
			let next = true
			let handleRe = {}
			options.complete = async (response) => {
				console.warn('响应', options.url, response)
				let originResp = response
				response.config = handleRe
				if (this.validateStatus(response)) { // 成功
					response = this.requestComFun(response)
					resolve(response)
				} else {
					response = await this.requestComFail(response)
					//TODO
					if (originResp.statusCode == 401 && !response.message && !response.code) {
						resolve(response)
					} else {
						reject(response)
					}

				}
			}
			const cancel = (t = '请求取消', config = options) => {
				const err = {
					errMsg: t,
					config: config
				}
				reject(err)
				next = false
			}

			handleRe = { ...await this.requestBeforeFun(options, cancel)
			}
			const _config = { ...handleRe
			}
			// 判断是否取消请求
			if (!next) return
			// 路径转化
			let mergeUrl = Request.isAbsoluteUrl(options.url) ? options.url : (options.baseUrl + options.url)
			if (JSON.stringify(options.params) !== '{}') {
				const paramsH = Request.addQueryString(options.params)
				mergeUrl += mergeUrl.indexOf('?') === -1 ? `?${paramsH}` : `&${paramsH}`
			}
			_config.url = mergeUrl
			console.warn('请求前:', _config.url, { ..._config.data,
				..._config.params
			})
			uni.request(_config)
		})
	}

	get(url, data, options = {}) {
		if (data) {
			options.params = data
		}
		return this.request({
			url,
			method: 'GET',
			...options
		})
	}

	post(url, data, options = {}) {
		return this.request({
			url,
			data,
			method: 'POST',
			...options
		})
	}
	put(url, data, options = {}) {
		return this.request({
			url,
			data,
			method: 'PUT',
			...options
		})
	}

}
